<template>
  <el-card
    shadow="hover"
    class="monitor-panel"
    :class="{ 'panel-error': hasOfflineService }"
  >
    <div class="panel-header">
      <h3 class="client-id">{{ clientId }}</h3>
      <div class="last-update">最后更新: {{ lastUpdateTime }}</div>
    </div>

    <!-- 服务状态 -->
    <div class="services-container">
      <el-tooltip
        v-for="service in services"
        :key="service.serviceName"
        :content="getServiceDetails(service)"
        placement="top"
        effect="dark"
      >
        <div
          class="service-card"
          :class="{ 'service-healthy': service.healthy, 'service-unhealthy': !service.healthy }"
        >
          <div class="service-name">{{ service.serviceName }}</div>
          <div class="service-status">
            <el-tag 
              :type="service.healthy ? 'success' : 'danger'" 
              effect="dark"
              size="small"
            >
              {{ service.healthy ? '正常' : '离线' }}
            </el-tag>
          </div>
        </div>
      </el-tooltip>
    </div>

    <!-- 图表 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :xs="24" :sm="8" class="chart-col">
        <div ref="cpuChart" class="chart-container"></div>
      </el-col>

      <el-col :xs="24" :sm="8" class="chart-col">
        <div ref="memoryChart" class="chart-container"></div>
      </el-col>

      <el-col :xs="24" :sm="8" class="chart-col">
        <div ref="diskChart" class="chart-container"></div>
      </el-col>
    </el-row>
  </el-card>
</template>

<script setup>
import { ref, onMounted, watch, onBeforeUnmount, computed } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
  clientId: String,
  systemStatus: Object,
  services: Array
});

const cpuChart = ref(null);
const memoryChart = ref(null);
const diskChart = ref(null);
const lastUpdateTime = ref('');

let cpuEchart, memoryEchart, diskEchart;
let updateTimer;

// 计算属性：是否有离线服务
const hasOfflineService = computed(() => {
  return props.services.some(service => !service.healthy);
});

// 获取服务详情
function getServiceDetails(service) {
  return `服务: ${service.serviceName}\n状态: ${service.healthy ? '正常' : '离线'}\n更新时间: ${lastUpdateTime.value}`;
}

// 初始化图表
function initCharts() {
  if (!cpuEchart && cpuChart.value) cpuEchart = echarts.init(cpuChart.value);
  if (!memoryEchart && memoryChart.value) memoryEchart = echarts.init(memoryChart.value);
  if (!diskEchart && diskChart.value) diskEchart = echarts.init(diskChart.value);
}

// 更新图表数据
function updateCharts() {
  if (!props.systemStatus) return;
  
  const { cpuUsage, memoryUsage, disks } = props.systemStatus;
  
  // 更新时间
  lastUpdateTime.value = new Date().toLocaleString();

  // 磁盘使用率图表
  diskEchart.setOption({
    title: {
      text: '磁盘使用率',
      left: 'center',
      textStyle: { color: '#fff', fontSize: 14, fontWeight: 'bold' }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      textStyle: { color: '#fff' },
      formatter: function (params) {
        const d = disks[params[0].dataIndex];
        return `
        <b>${d.path}</b><br/>
        使用率: ${d.usagePercent}%<br/>
        总空间: ${d.totalSpace}G<br/>
        剩余空间: ${d.freeSpace}G
      `;
      }
    },
    xAxis: {
      type: 'category',
      data: disks.map(d => d.path),
      axisLabel: { 
        color: '#fff',
        rotate: 45,
        interval: 0,
        fontSize: 10
      },
      axisLine: { lineStyle: { color: '#333' } }
    },
    yAxis: {
      type: 'value',
      max: 100,
      axisLabel: { 
        color: '#fff',
        formatter: '{value}%',
        fontSize: 10
      },
      axisLine: { lineStyle: { color: '#333' } },
      splitLine: { lineStyle: { color: '#333' } }
    },
    series: [{
      type: 'bar',
      data: disks.map(d => ({
        value: d.usagePercent,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: d.usagePercent > 80 ? '#ff4d4f' : '#52c41a' },
            { offset: 1, color: d.usagePercent > 80 ? '#ff7875' : '#95de64' }
          ]),
          borderRadius: [4, 4, 0, 0]
        }
      })),
      label: {
        show: window.innerWidth > 768, // 只在大屏幕显示标签
        position: 'top',
        formatter: '{c}%',
        color: '#fff',
        fontSize: 10
      },
      animationDuration: 1000,
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  });

  // CPU使用率图表
  cpuEchart.setOption({
    title: {
      text: 'CPU 使用率', 
      left: 'center', 
      textStyle: { 
        color: '#fff',
        fontSize: 14,
        fontWeight: 'bold' 
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}% ({d}%)',
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      textStyle: { color: '#fff' }
    },
    legend: {
      orient: window.innerWidth > 600 ? 'vertical' : 'horizontal',
      left: window.innerWidth > 600 ? 'left' : 'bottom',
      textStyle: { color: '#fff', fontSize: 10 }
    },
    series: [{
      name: 'CPU使用情况',
      type: 'pie',
      radius: window.innerWidth > 600 ? ['40%', '70%'] : ['30%', '60%'],
      center: ['50%', '60%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#0a1f3d',
        borderWidth: 2
      },
      label: {
        show: window.innerWidth > 600, // 只在大屏幕显示标签
        formatter: '{b}: {d}%',
        color: '#fff',
        fontSize: 10
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 16,
          fontWeight: 'bold'
        },
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      },
      labelLine: {
        show: true
      },
      data: [
        {
          value: cpuUsage, 
          name: '已使用',
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#ff6c00' },
              { offset: 1, color: '#ff9800' }
            ])
          }
        },
        {
          value: 100 - cpuUsage, 
          name: '空闲',
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#0a3b86' },
              { offset: 1, color: '#1e66c0' }
            ])
          }
        }
      ],
      animationDuration: 1000,
      animationType: 'scale',
      animationEasing: 'elasticOut'
    }]
  });

  // 内存使用率图表
  memoryEchart.setOption({
    title: {
      text: '内存使用率', 
      left: 'center', 
      textStyle: { 
        color: '#fff',
        fontSize: 14,
        fontWeight: 'bold' 
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}% ({d}%)',
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      textStyle: { color: '#fff' }
    },
    legend: {
      orient: window.innerWidth > 600 ? 'vertical' : 'horizontal',
      left: window.innerWidth > 600 ? 'left' : 'bottom',
      textStyle: { color: '#fff', fontSize: 10 }
    },
    series: [{
      name: '内存使用情况',
      type: 'pie',
      radius: window.innerWidth > 600 ? ['40%', '70%'] : ['30%', '60%'],
      center: ['50%', '60%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#0a1f3d',
        borderWidth: 2
      },
      label: {
        show: window.innerWidth > 600, // 只在大屏幕显示标签
        formatter: '{b}: {d}%',
        color: '#fff',
        fontSize: 10
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 16,
          fontWeight: 'bold'
        },
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      },
      labelLine: {
        show: true
      },
      data: [
        {
          value: memoryUsage, 
          name: '已使用',
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#ff0000' },
              { offset: 1, color: '#ff4d4f' }
            ])
          }
        },
        {
          value: 100 - memoryUsage, 
          name: '空闲',
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#0040ff' },
              { offset: 1, color: '#40a9ff' }
            ])
          }
        }
      ],
      animationDuration: 1000,
      animationType: 'scale',
      animationEasing: 'elasticOut'
    }]
  });
}

// 页面挂载
onMounted(() => {
  // 等待DOM完全渲染后初始化图表
  setTimeout(() => {
    initCharts();
    updateCharts();
  }, 100);

  // 图表自适应窗口大小
  window.addEventListener('resize', handleResize);
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize);
  
  // 销毁图表实例，释放资源
  if (cpuEchart) {
    cpuEchart.dispose();
  }
  if (memoryEchart) {
    memoryEchart.dispose();
  }
  if (diskEchart) {
    diskEchart.dispose();
  }
  
  // 清理定时器
  if (updateTimer) {
    clearTimeout(updateTimer);
  }
});

function handleResize() {
  if (cpuEchart) cpuEchart.resize();
  if (memoryEchart) memoryEchart.resize();
  if (diskEchart) diskEchart.resize();
}

// 监听 systemStatus 更新
watch(() => props.systemStatus, () => {
  if (props.systemStatus) {
    // 防抖处理，避免频繁更新
    if (updateTimer) {
      clearTimeout(updateTimer);
    }
    updateTimer = setTimeout(() => {
      updateCharts();
    }, 100);
  }
}, { deep: true });

// 监听组件挂载状态变化，确保图表正确渲染
watch([cpuChart, memoryChart, diskChart], () => {
  initCharts();
  updateCharts();
});
</script>

<style scoped>
.monitor-panel {
  height: auto;
  background: #0a1f3d;
  color: #fff;
  padding: 20px;
  margin-bottom: 40px;
  border-radius: 12px;
  border: 1px solid transparent;
  transition: all 0.3s ease;
  overflow-x: hidden; /* 防止水平滚动 */
}

.monitor-panel.panel-error {
  border-color: #ff4d4f;
  box-shadow: 0 0 20px rgba(255, 77, 79, 0.2);
}

.monitor-panel:hover {
  box-shadow: 0 4px 20px rgba(0, 160, 255, 0.3);
  transform: translateY(-2px);
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #333;
}

.client-id {
  font-size: 20px;
  font-weight: bold;
  margin: 0;
  color: #40a9ff;
}

.last-update {
  font-size: 12px;
  color: #999;
}

.services-container {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 20px;
  width: 100%;
}

.service-card {
  flex: 0 0 calc(33.333% - 8px);
  min-width: 150px;
  text-align: center;
  padding: 12px;
  border-radius: 8px;
  transition: all 0.3s ease;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.service-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  transition: width 0.3s ease;
  width: 100%;
}

.service-card.service-healthy {
  background: linear-gradient(135deg, rgba(82, 196, 26, 0.1) 0%, rgba(82, 196, 26, 0.05) 100%);
  border: 1px solid rgba(82, 196, 26, 0.3);
}

.service-card.service-healthy::before {
  background: #52c41a;
}

.service-card.service-unhealthy {
  background: linear-gradient(135deg, rgba(255, 77, 79, 0.1) 0%, rgba(255, 77, 79, 0.05) 100%);
  border: 1px solid rgba(255, 77, 79, 0.3);
}

.service-card.service-unhealthy::before {
  background: #ff4d4f;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
  100% {
    opacity: 1;
  }
}

.service-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

.service-name {
  font-weight: bold;
  margin-bottom: 8px;
  font-size: 14px;
}

.services-container {
  margin-bottom: 25px;
}

.charts-row {
  margin-top: 20px;
}

.chart-col {
  margin-bottom: 20px;
}

.chart-container {
  width: 100%;
  height: 280px;
  border-radius: 8px;
  overflow: hidden;
  background: rgba(255, 255, 255, 0.02);
  padding: 10px;
}

/* 响应式设计 - 优化小笔记本显示 */
@media (max-width: 1024px) {
  /* 适用于10英寸小笔记本 */
  .monitor-panel {
    padding: 15px;
    margin-bottom: 30px;
  }
  
  .chart-container {
    height: 200px;
  }
  
  .client-id {
    font-size: 18px;
  }
}

@media (max-width: 768px) {
  .service-card {
    flex: 0 0 calc(50% - 6px);
  }
  
  .panel-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .chart-container {
    height: 180px;
  }
  
  .services-container {
    gap: 10px;
  }
}

@media (max-width: 600px) {
  /* 适用于更小的笔记本和手机 */
  .service-card {
    flex: 0 0 100%;
  }
  
  .chart-container {
    height: 150px;
    padding: 5px;
  }
  
  .monitor-panel {
    padding: 10px;
    margin-bottom: 20px;
  }
  
  .client-id {
    font-size: 16px;
  }
  
  .services-container {
    gap: 8px;
  }
  
  .service-card {
    padding: 8px;
    min-width: auto;
  }
  
  .service-name {
    font-size: 12px;
  }
}

/* 额外优化小屏幕下的图表显示 */
@media (max-width: 480px) {
  .chart-container {
    height: 140px;
  }
  
  .last-update {
    font-size: 11px;
  }
}
</style>
